package com.dvj.gulimall.product.web;

import com.dvj.gulimall.product.entity.CategoryEntity;
import com.dvj.gulimall.product.service.CategoryService;
import com.dvj.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Dvj
 * @date 2021/7/30 21:26
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        // 查出所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        model.addAttribute("categorys", categoryEntities);

        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        // 1.获取锁，只要锁名一样即为同一把锁
        RLock lock = redisson.getLock("my-lock");

        // 2.加锁
        //lock.lock(); // 阻塞式等待
        // 锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s
        lock.lock(10, TimeUnit.SECONDS); // 10秒自动解锁，自动解锁时间一定要大于业务时间
        // 最佳实战：使用指定超时时间，仍然没完成一般认为业务出异常了
        try {
            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 3.解锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 保证一定能读到最新数据，修改期间，写锁是排他锁，读锁是共享锁
     *
     * @return
     */
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        System.out.println(lock);
        String s = "";
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            // 1.改数据加写锁，读数据加读锁
            System.out.println("获取写锁..." + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(10000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放写锁..." + Thread.currentThread().getId());
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        System.out.println(lock);
        String s = "";
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            System.out.println("获取读锁..." + Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放读锁..." + Thread.currentThread().getId());
            rLock.unlock();
        }
        return s;
    }

    /**
     * 车库停车，3车位
     * 信号量也可以用作限流
     *
     * @return
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() {
        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire(); // 获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        if (b) {
            System.out.println("复杂业务");
        }
        return "ok=》" + b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        park.release(); // 获取一个信号，获取一个值，占一个车位
        return "ok";
    }

    /**
     * 放假锁门
     * 所有班级走完，才可以锁大门
     *
     * @return
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await(); // 等待闭锁都完成

        return "放假了";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();

        return id + "班的人走了...";
    }
}
